import { useChooseDir } from 'renderer/hook/useChoose';
import { useSelector, useDispatch } from 'react-redux';
import { useEffect } from 'react';
import { Dispatch } from 'redux';
import { Progress } from 'antd';
import MLog from 'renderer/util/main-log';
import { MinusCountButton } from '../../components/MinusCountButton';
import {
  FeatureName,
  Task,
  TaskName,
} from '../../../main/biz/ipc/feature.const';
import { GlobalState } from '../../biz/state-manager/global-state-context.state';
import {
  COMMON_CLEAR_FEATURE_PROGRESS,
  ProgressAction,
} from '../../biz/state-manager/action-type.const';
import { Button } from 'antd';
import './index.css';

const TAG = 'CsvToExcel';

function CsvToExcel() {
  // const [scanDir, startChooseScanDir] = useChooseDir('/Users/shenzhengyuan/Desktop/in');
  const [scanDir, startChooseScanDir] = useChooseDir('');
  const [exportDir, startChooseExportDir] = useChooseDir('');
  const dispatch = useDispatch<Dispatch<ProgressAction>>();
  const featureProgress: number = useSelector((state: GlobalState) => {
    const progressInfo = state.progressState.progressInfos
      .filter((pregressInfo) => {
        return (
          pregressInfo.task.taskName === TaskName.CSV_TO_EXCEL &&
          pregressInfo.task.featureName === FeatureName.CSV_TO_EXCEL
        );
      })
      .shift();
    return progressInfo ? progressInfo.progress : 0;
  });
  const doCsvToExcel = async () => {
    if (scanDir === '') {
      window.electronAPI.ipcRenderer.showError('错误', '需要选择扫描路径');
      return;
    }
    if (exportDir === '') {
      window.electronAPI.ipcRenderer.showError('错误', '需要选择导出路径');
      return;
    }
    window.electronAPI.ipcRenderer.csvToExcel(
      new Task(FeatureName.CSV_TO_EXCEL, TaskName.CSV_TO_EXCEL),
      scanDir,
      exportDir
    );
  };
  useEffect(() => {
    const clearProgress = () => {
      dispatch({
        type: COMMON_CLEAR_FEATURE_PROGRESS,
        progressInfo: {
          task: new Task(FeatureName.CSV_TO_EXCEL, TaskName.CSV_TO_EXCEL),
          progress: 0,
        },
      });
    };
    clearProgress();
    return clearProgress;
  }, [scanDir, exportDir, dispatch]);
  useEffect(() => {
    if (featureProgress === 1) {
      window.electronAPI.ipcRenderer.showMessage('提示', '导出成功');
    }
  }, [featureProgress]);
  return (
    <div id="csv2excel-container">
      <h1>Csv批量转换为Excel</h1>
      <div>
        <Button onClick={startChooseScanDir}>1.选择扫描的文件夹</Button>
        <div>扫描路径: {scanDir}</div>
      </div>
      <div>
        <Button onClick={startChooseExportDir}>2.导出的文件夹</Button>
        <div>导出路径: {exportDir}</div>
      </div>
      <div>
        <MinusCountButton type="primary" onCustomClick={doCsvToExcel}>
          3.执行转换
        </MinusCountButton>
      </div>
      <Progress
        percent={featureProgress * 100}
        format={(percent) => `${percent?.toFixed(1)}%`}
      />
    </div>
  );
}
export default CsvToExcel;
